package com.example.crm.service;

import com.example.crm.entity.Right;
import com.example.crm.entity.Role;
import com.example.crm.entity.User;
import com.example.crm.repository.RightRepository;
import com.example.crm.repository.RoleRepository;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lenovo
 */
@Service("roleService")
public class IRoleServiceImpl implements IRoleService {
    @Resource
    private RoleRepository roleRepository;
    @Resource
    private RightRepository rightRepository;

    @Override
    public List<Role> findAllRoles() {
        return roleRepository.findAll();
    }

    @Override
    public List<Right> findAllRights() {
        return rightRepository.findAll();
    }

    @Override
    public List<Right> findRightsByRole(Role role) {
        return rightRepository.findRightsByRolesOrderByRightCode(role);
    }

    @Override
    public Role saveRole(Role role) {
        return roleRepository.save(role);
    }

    @Override
    public void deleteRoleById(Long roleId) {
        roleRepository.deleteById(roleId);
    }

    @Override
    public void deleteRole(Role role) {
        roleRepository.delete(role);
    }

    @Override
    public Role getRole(Long roleId) {
        return roleRepository.findById(roleId).get();
    }

    @Override
    public Page<Role> findRole(String roleName, Pageable pageable) {
        return roleRepository.findRolesByRoleNameLike("%"+roleName+"%",pageable);
    }

    @Override
    public Role findRoleByUsers(User user) {
        return roleRepository.findRoleByUsers(user);
    }

    public Map<String, String> loadFilterChainDefinitions() {
        //必须使用LinkedHashMap(有序集合)
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //配置可以访问的资源(URL):静态资源
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        ////注销过滤器，自动注销
        filterChainDefinitionMap.put("/logout", "anon");
        //动态授权
        List<Right> rights = findAllRights();
        for (Right right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightCode() + "]");
            }
        }
        //配置认证访问：其他资源(URL)必须认证通过才能访问
        //必须放在过滤器链的最后面
        filterChainDefinitionMap.put("/**", "authc");
        return filterChainDefinitionMap;
    }

    @Override
    public void reloadFilterChainDefinitions(){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext = request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("shiroFilterFactory");
            synchronized(shiroFilter){
                //获取过滤器管理
                PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                //清空初始权限配置
                manager.getFilterChains().clear();
                //重新加载动态权限，配置权限验证规则
                Map<String,String> chains = loadFilterChainDefinitions();
                for (Map.Entry<String, String> entry : chains.entrySet()) {
                    String url = entry.getKey();
                    String chainDefinition = entry.getValue().trim().replace(" "," ");
                    manager.createChain(url,chainDefinition);
                }
                System.out.println("更新权限成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
